package gemini.castor.ui.server.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

public class UploadImageFileServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		super.doGet(req, resp);
	}

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		try {
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);

			upload.setSizeMax(1000000);
			res.setContentType("text/plain");
			
			PrintWriter out = res.getWriter();
			try {
				List<FileItem> items = upload.parseRequest(req);
				for (FileItem item : items) {

					if (!item.isFormField()) {

						String fileName = item.getName();
						if (fileName != null) {
							fileName = FilenameUtils.getName(fileName);
						}
						
						File uploadedFile = new File(req.getRealPath("/") + "images//product//", fileName);
						if (uploadedFile.createNewFile()) {
							item.write(uploadedFile);
							//res.setStatus(HttpServletResponse.SC_CREATED);
							out.print("images/product/" + fileName);
						} else {
							out.print("The file already exists in repository.");
						}
						
						//res.flushBuffer();
					}
				}
			} catch (SizeLimitExceededException e) {
				out.println("You exceeded the maximum size ("
						+ e.getPermittedSize() + ") of the file ("
						+ e.getActualSize() + ")");
			}
		} catch (Exception ex) {
			throw new ServletException(ex);
		}
	}

}
